"""
Copyright (c) 2023 - present SKbioinfo
"""
import re
from flask_restful import Resource
from flask import request,jsonify
from apps.API.utils.log_helper import lg
from apps.API.connector.db_common import *
from apps.API.common.common_time import *
from apps.API.common.db_table_config import *
from apps.API.common.common_generate_id import id_generator

class interfaceReceiptID(Resource):
    def put(self,id):
        try:
            ### SQL: update receipt sql ###
            update_receipt_sql = '''
                UPDATE {table_name} SET 
                    receipt_amount = {receipt_amount},
                    return_amount = {return_amount}
                WHERE receipt_id = \"{receipt_id}\" 
            '''.format(
                table_name=common_tables.receipt_db["name"],
                receipt_amount=request.json["receipt_amount"],
                return_amount=request.json["return_amount"],
                receipt_id=request.json["receipt_id"]
            )
            update_info(update_receipt_sql)
            return 202
        except Exception as e:
            lg.error(e)
            return 400

class interfaceReceipt(Resource):
    def __init__(self):
        self.gen=id_generator(name=common_tables.receipt_db["name"])
    # @login_required
    def get(self):
        try:
            cols = '''
                t1.id,
                t1.receipt_id,
                t1.service_id,
                t1.service_name,
                t1.locale,
                t1.project_id,
                t1.sample_id,
                t1.receipt_amount,
                t1.return_amount,
                t1.create_time,
                t1.reason,
                t1.rec_stat,
                t1.dflag,
                t1.rflag,
                t1.applicant,
                t2.status,
                t2.sample_name,
                t2.sample_amount,
                t2.disp_amount,
                t2.disp_size,
                t2.instock_time,
                t2.current_amount,
                t2.lot_number,
                t2.size
            '''
            ### SQL: Receipt infos ###
            receipt_query_sql='''
                SELECT {cols} FROM {table_one} as t1 
                LEFT JOIN {table_two} as t2
                ON t1.{col_one}=t2.{col_one}
            '''.format(
                cols=cols,
                table_one=common_tables.receipt_db["name"],
                table_two=common_tables.sample_db["name"],
                col_one="sample_id"  
            )
            receipt_info=dic_query_info(receipt_query_sql)
            receipts=[]
            for receipt in receipt_info:
                # receipt["create_time"]=shift_format(receipt["create_time"])
                # receipt["instock_time"]=shift_format(receipt["instock_time"])
                receipts.append(receipt) 
            response=jsonify(receipts)
            response.status=202
            return response
        except Exception as e:
            lg.error(e)
        
    def post(self):
        try:
            cols = '''
                receipt_id,
                service_id,
                service_name,
                locale,
                project_id,
                sample_id,
                receipt_amount,
                reason,
                create_time,
                modify_time,
                rec_stat,
                dflag,
                return_amount,
                rflag,
                applicant
            '''
            receipt_prefix=self.gen.generate_prefix(tag="receipt")
            for receipt in request.json:
                ### SQL: add receipt infos to database ###
                receipt_id=self.gen.generate_id(col="receipt_id")
                receipt_id=int(receipt_id["receipt_id"]) + 1
                values='''
                    \"{receipt_id}\",
                    \"{service_id}\",
                    \"{service_name}\",
                    \"{locale}\",
                    \"{project_id}\",
                    \"{sample_id}\",
                    {receipt_amount},
                    \"{reason}\",
                    \"{create_time}\",
                    \"{modify_time}\",
                    {rec_stat},
                    {dflag},
                    {return_amount},
                    {rflag},
                    \"{applicant}\"
                '''.format(
                        receipt_id=receipt_prefix + str(receipt_id),
                        service_id=receipt["service"].split(":")[0],
                        service_name=receipt["service"].split(":")[1],
                        locale=receipt["locale"],
                        project_id=receipt["project_id"],
                        sample_id=receipt["sample_id"],
                        receipt_amount=receipt["receipt_amount"],
                        reason=receipt["reason"],
                        create_time=get_current_time(),
                        modify_time=get_current_time(),
                        rec_stat=0,
                        dflag=receipt["dflag"],
                        return_amount=0,
                        rflag=-1,
                        applicant=receipt["applicant"]
                )
                ### SQL: add receipt ###
                add_receipt_sql = '''
                    INSERT INTO {table_name} ({cols}) VALUES ({values})
                '''.format(
                    table_name=common_tables.receipt_db["name"],
                    cols=cols,
                    values=values
                )
                ### SQL: update sample status ###
                update_status_sql='''
                    UPDATE {table_name} SET {col_one}={status} WHERE {col_two}=\"{sample_id}\"
                '''.format(
                    table_name=common_tables.sample_db["name"],
                    col_one="status",
                    col_two="sample_id",
                    sample_id=receipt["sample_id"],
                    status=3
                )
                ### STEP 1: instock receipt ###
                add_info(add_receipt_sql)
                ### STEP 3: update stock status ###
                update_info(update_status_sql) 
            response=jsonify({"status":202})
            response.status=202
            return response
        except Exception as e:
            response=jsonify({"status":400})
            return response
  
class interfaceReturn(Resource):
    def post(self):
        try:
            for info in request.json:
                ### SQL: update receipt status ###
                update_status_sql='''
                        UPDATE {table_name} SET 
                            {col_one}={rec_stat},
                            {col_two}={return_amount},
                            rflag={rflag}
                        WHERE {col_three}=\"{receipt_id}\"
                    '''.format(
                        table_name=common_tables.receipt_db["name"],
                        col_one="rec_stat",
                        col_two="return_amount",
                        col_three="receipt_id",
                        receipt_id=info["receipt_id"],
                        return_amount=info["return_amount"],
                        rflag=info["rflag"],
                        rec_stat=3
                )
                update_info(update_status_sql)
            return 202
        except Exception as e:
            response=jsonify({"status":400})
            return response
      
class interfaceQueryReceipt(Resource):
    def post(self):
        try:
            select_proj_ids = request.json["project_id"]
            query_proj_list = ""
            for project_id in select_proj_ids:
                query_proj_list += "\"" + project_id + "\","
            query_proj_list=query_proj_list.rstrip(",")
            ### SQL: query project ###
            cols = '''
                tb1.id,
                tb1.receipt_id,
                tb1.service_id,
                tb1.service_name,
                tb1.locale,
                tb1.extra_info,
                tb1.project_id,
                tb1.sample_id,
                tb1.receipt_amount,
                tb1.return_amount,
                tb1.dflag,
                tb1.rflag,
                tb1.extra_info,
                tb1.reason,
                tb1.applicant,
                tb1.create_time,
                tb1.modify_time,
                tb1.rec_stat,
                tb2.status,
                tb2.disp_amount,
                tb2.disp_size,
                tb2.current_amount,
                tb2.sample_name,
                tb2.lot_number,
                tb2.size
            '''
            ### SQL: query project sql ###
            query_proj_sql = '''
                SELECT {cols} FROM {table_one} as tb1 
                LEFT JOIN {table_two} as tb2
                ON tb1.{col} = tb2.{col}
                WHERE {select_col} IN ({select_values}) 
            '''.format(
                cols=cols,
                table_one=common_tables.receipt_db["name"],
                table_two=common_tables.sample_db["name"],
                col="sample_id",
                select_col="tb1.project_id",
                select_values=query_proj_list
            )
            base_infos=dic_query_info(query_proj_sql)
            proj_infos=[]
            for info in base_infos:
                info["create_time"]=shift_format(info["create_time"])
                proj_infos.append(info)
            response=jsonify(proj_infos)
            response.status=202
            return response
        except Exception as e:
            lg.error(e)
            
class interfaceReceiptCheck(Resource):
    def post(self,action):
        try:
            if action=="receive":
                ### SQL: update receipt statu ###
                for sam_id,value in request.json.items():
                    currentAmount=0
                    totalRawReceipt=0
                    currentDisAmount=0
                    totalDispReceipt=0
                    for receipt in value:
                        currentAmount=receipt["current_amount"]
                        currentDisAmount=receipt["disp_amount"]
                        if receipt["dflag"] == 0:
                            totalRawReceipt = totalRawReceipt + receipt["receipt_amount"]
                        elif receipt["dflag"] == 1:
                            totalDispReceipt = totalDispReceipt + receipt["receipt_amount"]
                    if totalRawReceipt > currentAmount or totalDispReceipt > currentDisAmount:
                        return 203
                    else:
                        for receipt in value:
                            update_receive_sql='''
                                UPDATE {table_name} SET rec_stat={value} WHERE receipt_id=\"{receipt_id}\"
                            '''.format(
                                table_name=common_tables.receipt_db["name"],
                                value=1,
                                receipt_id=receipt["receipt_id"]
                            )
                            update_info(update_receive_sql)
                        ### SQL: update sample amount ###
                        update_current_amount_sql='''
                            UPDATE {table_name} SET {col}={totalAmount} WHERE sample_id=\"{sample_id}\"
                        '''.format(
                            table_name=common_tables.sample_db["name"],
                            col="current_amount",
                            totalAmount= currentAmount - totalRawReceipt,
                            sample_id=sam_id
                        )
                        update_info(update_current_amount_sql)
                        ### SQL: update dispense amount ###
                        update_disp_amount_sql='''
                            UPDATE {table_name} SET {col}={totalAmount} WHERE sample_id=\"{sample_id}\"
                        '''.format(
                            table_name=common_tables.sample_db["name"],
                            col="disp_amount",
                            totalAmount= currentDisAmount - totalDispReceipt,
                            sample_id=sam_id
                        )
                        update_info(update_disp_amount_sql)
                # ### STEP 2: update current amount ###
                update_info(update_current_amount_sql)
                return 202
            if action=='return':
                for sam_id,value in request.json.items():
                    totalRawReturn=0
                    totalDsipReturn=0
                    currentAmount=0
                    currentDisAmount=0
                    for receipt in value:
                        currentDisAmount=receipt["disp_amount"]
                        currentAmount=receipt["current_amount"]
                        if receipt["rflag"] == 1:
                            totalDsipReturn = totalDsipReturn + receipt["return_amount"]
                        elif receipt["rflag"] == 0:
                            totalRawReturn = totalRawReturn + receipt["return_amount"]
                        ### SQL: update receipt statu ###
                        update_return_status_sql='''
                            UPDATE {table_name} SET rec_stat={value} WHERE receipt_id=\"{receipt_id}\"
                        '''.format(
                            table_name=common_tables.receipt_db["name"],
                            value=4,
                            receipt_id=receipt["receipt_id"]
                        )
                        ### STEP 1: update sample statu ###
                        update_info(update_return_status_sql)
                    ### SQL: update sample amount ###   
                    update_current_amount_sql='''
                        UPDATE {table_name} SET {col}={totalAmount} WHERE sample_id=\"{sample_id}\"
                    '''.format(
                        table_name=common_tables.sample_db["name"],
                        col="current_amount",
                        totalAmount= currentAmount + totalRawReturn,
                        sample_id=sam_id
                    )
                    ### STEP 2: update raw current amount ###
                    update_info(update_current_amount_sql)
                    ### SQL: update sample dispense amount ### 
                    update_disp_amount_sql='''
                        UPDATE {table_name} SET {col}={totalAmount} WHERE sample_id=\"{sample_id}\"
                    '''.format(
                        table_name=common_tables.sample_db["name"],
                        col="disp_amount",
                        totalAmount= currentDisAmount + totalDsipReturn,
                        sample_id=sam_id
                    )
                    ### STEP 3: update dispense amount ###
                    update_info(update_disp_amount_sql)
                return 202
            if action == 'receipt_fail':
                update_receipt_fail = '''
                    UPDATE {table_name} SET rec_stat={value} WHERE receipt_id=\"{receipt_id}\" 
                '''.format(
                        table_name = common_tables.receipt_db["name"],
                        value=2,
                        receipt_id=request.json["receipt_id"]
                )
                update_info(update_receipt_fail)
                return 202
            if action == 'return_fail':
                ### SQL: update receipt status ###
                update_return_fail = '''
                    UPDATE {table_name} SET rec_stat={value} WHERE receipt_id=\"{receipt_id}\" 
                '''.format(
                        table_name = common_tables.receipt_db["name"],
                        value=5,
                        receipt_id=request.json["receipt_id"]
                )
                update_info(update_return_fail)
                return 202
        except Exception as e:
            lg.error(e)
            return 404

class interfaceRecheck(Resource):
    def post(self,action):
        if action == "receipt_recheck":
            ### SQL: update receipt status ###
            update_receipt_recheck = '''
                UPDATE {table_name} SET rec_stat={value} WHERE receipt_id=\"{receipt_id}\" 
            '''.format(
                    table_name = common_tables.receipt_db["name"],
                    value=0,
                    receipt_id=request.json["receipt_id"]
            )
            ### STEP 1: update receipt statu ###
            update_info(update_receipt_recheck)
            ### SQL: update receipt info ###
            update_receipt_sql = '''
                UPDATE {table_name} SET 
                    receipt_amount={receipt_amount},
                    reason=\"{reason}\",
                    locale=\"{locale}\",
                    service_name=\"{service}\",
                    extra_info=\"{extra_info}\"
                WHERE receipt_id=\"{receipt_id}\"
            '''.format(
                table_name = common_tables.receipt_db["name"],
                receipt_amount=request.json["receipt_amount"],
                reason=request.json["reason"],
                locale=request.json["locale"],
                service=request.json["service"].split(":")[1],
                extra_info=request.json["extra_info"],
                receipt_id=request.json["receipt_id"],
            )
            ### STEP 2: update receipt recheck ###
            update_info(update_receipt_sql)
            return 202
        if action == "return_recheck":
            update_return_recheck = '''
                UPDATE {table_name} SET rec_stat={value} WHERE receipt_id=\"{receipt_id}\" 
            '''.format(
                    table_name = common_tables.receipt_db["name"],
                    value=3,
                    receipt_id=request.json["receipt_id"]
            )
            ### STEP 1: update receipt return ###
            update_info(update_return_recheck)
            update_receipt_sql = '''
                UPDATE {table_name} SET 
                    receipt_amount={receipt_amount},
                    reason=\"{reason}\",
                    locale=\"{locale}\",
                    service_name=\"{service}\",
                WHERE receipt_id=\"{receipt_id}\"
            '''.format(
                table_name = common_tables.receipt_db["name"],
                receipt_amount=request.json["receipt_amount"],
                reason=request.json["reason"],
                locale=request.json["locale"],
                service=request.json["service_name"],
                receipt_id=request.json["receipt_id"],
            )
            return 202